﻿using Coater.Helper;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Coater
{
    public partial class FormRecipeList : Form
    {
        public RecipeInfo recipe { get; set; }
        public string recipeName { get; set; }

        DirectoryInfo recipeDirectory { get; set; }

        public FormRecipeList()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            recipeName = this.liRecipe.Text;
            recipe = (RecipeInfo)this.liRecipe.SelectedValue;
            this.DialogResult = DialogResult.OK;
        }

        private void FormRecipeList_Load(object sender, EventArgs e)
        {
            try
            {
                recipeDirectory = new DirectoryInfo(DeviceContext.Instance.Config.RecipePath);
                string path = recipeDirectory.FullName;
                ToolTip toolTipDirectoryPath = new ToolTip();
                toolTipDirectoryPath.AutoPopDelay = 5000; // 自动消失延迟时间
                toolTipDirectoryPath.InitialDelay = 100; // 鼠标移入控件后多久显示ToolTip
                toolTipDirectoryPath.ReshowDelay = 100; // 鼠标移出控件再移入后多久重新显示ToolTip
                toolTipDirectoryPath.ShowAlways = true; // 即使鼠标悬停在没有文字的控件上也要显示ToolTip
                                                        // 添加ToolTip到Label
                toolTipDirectoryPath.SetToolTip(this.lbDirectoryPath, path);
                path = path.Length > 30 ? path.Substring(0, 40) + "..." : path;
                this.lbDirectoryPath.Text = path;

                var fileInfos = recipeDirectory.GetFiles().OrderBy(f => f.Name);
                DataTable dt = new DataTable();
                dt.Columns.Add("key", typeof(string));
                dt.Columns.Add("value", typeof(RecipeInfo));

                foreach (var fileInfo in fileInfos)
                {
                    dt.Rows.Add(Path.GetFileNameWithoutExtension(fileInfo.Name), XMLHelper.GetSettings_FullName<RecipeInfo>(fileInfo.FullName));
                }
                this.liRecipe.DataSource = dt;
                this.liRecipe.DisplayMember = "key";
                this.liRecipe.ValueMember = "value";
                this.liRecipe.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.Error(ex);
                MessageBox.Show(ex.Message, "Error");
            }
        }
    }
}
